<template>
  <div class="video-container">
    <video
      preload="auto"
      controls
      loop
      :poster="pageData.videoInfo.cover"
      class="video-player"
      ref="videoPlayer"
      @pause="onVideoPause"
    >
      <source :src="pageData.videoInfo.url" type="video/mp4" />
    </video>

    <!-- 热门直播 -->
    <div class="hot-live">
      <div class="left">
        <div class="avatar">
          <img
            :src="avatar"
            :class="`avatar-${index}`"
            v-for="(avatar, index) in pageData.avatars"
            :key="index"
          />
        </div>
      </div>

      <div class="right">热门直播</div>
    </div>

    <!-- 中间播放按钮 -->
    <div class="player-button" @click="playVideo" v-if="!isPlaying">
      <img src="@/assets/clip_play.png" />
    </div>

    <!-- 作者和社交媒体信息 -->
    <div class="comments-status">
      <div class="left">
        <div class="comments">
          <comments :comments="pageData.comments" :duration="2" :scrollDistance="250" />
        </div>

        <div class="actor"></div>
      </div>

      <div class="right">
        <div class="avatar"></div>
        <div class="collect">
          <van-icon name="star" size="40" />
          <p>收藏</p>
        </div>

        <div class="reply">
          <van-icon name="chat" size="40" />
          <p>{{ pageData.commentCount }}</p>
        </div>

        <div class="cart">
          <van-icon name="cart" size="40" />
          <p>购物车</p>
        </div>
      </div>
    </div>

    <div class="recommend">热推荐产品</div>
  </div>
</template>

<script setup>
import Comments from '../clip/Comments.vue'
import { getLiveDetail } from '@/api/index.js'
import { ref, onMounted, reactive, nextTick, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
// const videoPlayer = useTemplateRef('player')

//接收 首页 传递来的参数
const itemId = ref(route.query.itemId)
const actorId = ref(route.query.actorId)

const videoPlayer = ref(null)
const isPlaying = ref(false)

const pageData = reactive({
  avatars: [],
  actorInfo: {},
  itemInfo: {},
  videoInfo: { cover: '', url: '' },
  comments: [],
  commentCount: 0,
})

onMounted(async () => {
  // console.log('itemId,actorId:', itemId.value, actorId.value)

  const res = await getLiveDetail(itemId.value, actorId.value)
  const explain = res.data?.itemExplainList?.[0] || {}
  pageData.comments = explain.comments || []
  pageData.videoInfo = {
    cover: explain.videoInfo?.cover || '',
    url: explain.videoInfo?.url || '',
  }
  // console.log("live:", res);
  // videoUrl.value = res.data.videoUrl
  pageData.avatars = res.data.hotLink.avatars
  pageData.actorInfo = explain.actorInfo
  pageData.itemInfo = explain.itemInfo
  pageData.commentCount = explain.commentCount

  await nextTick()
  if (videoPlayer.value) {
    // 先移除旧事件监听防止重复
    videoPlayer.value.removeEventListener('loadeddata', handleVideoReady)
    // 设置新视频源后加载
    videoPlayer.value.load()
    // 添加元数据加载完成监听
    videoPlayer.value.addEventListener('loadeddata', handleVideoReady)
  }
})

onBeforeUnmount(() => {
  if (videoPlayer.value) {
    videoPlayer.value.removeEventListener('loadeddata', handleVideoReady)
    videoPlayer.value.removeEventListener('pause', onVideoPause)
  }
})

const handleVideoReady = () => {
  console.log('视频元数据已加载')
}

const onVideoPause = () => {
  isPlaying.value = false
}

const playVideo = async () => {
  try {
    if (videoPlayer.value.readyState < HTMLMediaElement.HAVE_METADATA) {
      console.warn('视频尚未加载元数据')
      await new Promise((resolve) => {
        videoPlayer.value.addEventListener('loadedmetadata', resolve, { once: true })
      })
    }

    await videoPlayer.value.play()
    isPlaying.value = true
    videoPlayer.value.focus()
  } catch (error) {
    console.error('播放失败:', error)
    // 可添加用户提示
    isPlaying.value = false
  }
}
</script>

<style lang="scss" scoped>
.video-container {
  position: relative;
  width: 100vw;
  height: 100vh;

  .video-player {
    position: relative;
    width: 100%;
    height: 100%;
  }

  .hot-live {
    position: absolute;
    top: 10px;
    left: 10px;
    display: flex;
    align-items: center;
    justify-content: center;

    .left {
      width: auto;
      height: 30px;

      .avatar {
        position: relative;
        width: 100%;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        padding-left: 15px;
        overflow-x: visible;
        white-space: nowrap;
        min-width: 90px;

        img {
          position: absolute;
          width: 30px;
          height: 30px;
          border: 0.5px solid #fff;
          border-radius: 50%;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); // 添加投影
          transition: all 0.3s ease; // 平滑过渡
        }

        @for $i from 0 through 4 {
          &.avatar-#{$i} {
            left: #{$i * 15}px;
            z-index: #{$i + 1};

            &:hover {
              transform: translateY(-5px) scale(1.1); // 悬停效果
              z-index: 999; // 悬停时置顶
            }
          }
        }
      }
    }

    .right {
      margin-left: 20px; // 与头像区保持间距
      font-size: 14px;
      color: #fff;
      text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
    }
  }

  .player-button {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 10;

    img {
      width: 50px;
      height: 50px;
    }
  }

  .comments-status {
    width: 100%;
    position: absolute;
    left: 0;
    bottom: 100px;
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    padding: 0 10px;
    box-sizing: border-box;

    .left {
      max-width: 250px;
      box-sizing: border-box;

      .comments {
        width: 100%;
        background-color: transparent;
      }
    }

    .right {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      justify-content: center;
      font-size: 12px;
      color: #fff;

      .collect {
        text-align: center;

        p {
          margin: 0;
        }
      }

      .reply {
        text-align: center;

        p {
          margin: 0;
        }
      }

      .cart {
        text-align: center;

        p {
          margin: 0;
        }
      }

      .van-icon {
        // color: #fff;
        display: block;
      }
    }
  }

  .recommend {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;

    border-radius: 0.08rem;
    background-color: rgba(0, 0, 0, 0.2);
    overflow: hidden;
  }
}
</style>
